package com.vuej.util;

import com.vuej.core.VueFileRenderCallback;
import com.vuej.exception.VuejException;

import javax.script.Bindings;


public class VueFileRenderCallbackWrapper implements VueFileRenderCallback {
    private final VueFileRenderCallback callback;
    private final ThreadLocal<VuejException> throwableThreadLocal = new ThreadLocal<>();

    public VueFileRenderCallbackWrapper(VueFileRenderCallback callback) {
        this.callback = callback;
    }

    public ThreadLocal<VuejException> getThrowableThreadLocal() {
        return throwableThreadLocal;
    }

    @Override
    public void onError(Bindings error) {
        try{
            callback.onError(error);
        }catch (Throwable e){
            VuejException vuejException = e instanceof VuejException ? (VuejException) e : new VuejException(e);
            throwableThreadLocal.set(vuejException);
            throw vuejException;
        }
    }

    @Override
    public void onSuccess(String result) {
        try {
            callback.onSuccess(result);
        } catch (Throwable e) {
            VuejException vuejException = e instanceof VuejException ? (VuejException) e : new VuejException(e);
            throwableThreadLocal.set(vuejException);
            throw vuejException;
        }
    }
}
